// pages/search/search.js
const app = getApp()
const http = require("../../config/api.js");
const user = require("../../utils/login.js");
Page({

  data: {
    name: true,
    bool: true,
    api: "",
    imgUrl: "",
    key: 1,//1剧名，2名家,
    searchValue: "",
    history: [],//搜索历史
    searchList: [],
    query: {
      cur: 1,
      pageSize: 10,
      userId: ""
    }
  },
  onShow: function() {
    this.setData({
      history: wx.getStorageSync("history") || [],
      ['query.userId']: app.globalData.userId,
      api: app.globalData.baseUrlApiTest,
      imgUrl: app.globalData.baseUrlImg,
      // searchValue: "",
      // name: true,
      // searchList: []
    })
    let time = Math.round(new Date().getTime());
    let log = {
      //日志类型：unite.通用业务；visit.访问数据；click.点击数据；order.订购数据；error.错误日志
      logType: "visit",
      msg: JSON.stringify({
        mac: app.globalData.userId,
        page: "xcxso",
        pageName: "梨园行搜索",
        time: time,
        appVersionName: "小程序",
        item: 65,
        nodeCode: "001000",
        project: "lyhad",
        userId: app.globalData.memberId,
        deviceId: app.globalData.userId,
        uuid: user.getUuid(),
        pageLevel: "1"
      })
    }
    this.uniteLog(log)
  },
  //顶部tab切换
  fnTotabSel(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      key: key,
      searchList: [],
      bool:true,
      history: wx.getStorageSync("history") || [],
      name: true,
      searchValue: ""
    })
  },
  // 输入搜索的文字
  fnSearchKey(e) {
    let searchValue = e.detail.value;
    if (!searchValue) {
      this.setData({
        name: true
      })
    }
    this.setData({
      searchValue: searchValue
    })
  },
  //点击×清楚搜索文字
  fnResetSearchKey() {
    this.setData({
      searchValue: "",
      searchList: [],
      name: true
    })
  },
  //清除搜索记录
  clearHistory() {
    this.setData({
      history: []
    })
    wx.setStorageSync("history", [])
  },
  // 搜索
  fnSearch() {
    let name = this.data.name;
    let that = this;
    let key = that.data.key;
    let _searchKey = that.data.searchValue;
    
    if(!name) {
      that.setData({
        searchList: [],
        bool: true,
        searchValue: "",
        name: true
      })
      return
    }
    if (!that.data.searchValue) {
      let msg = key == 1 ? "剧名" : "名家";
      wx.showToast({
        title: `请输入${msg}名称搜索`,
        icon: "none",
        duration: 2000
      })
      return
    }
    if (that.data.searchValue) {
      that.setData({
        name: false
      })
    }
    let history = wx.getStorageSync("history") || [];
    let historyArr = []
    history.push(that.data.searchValue)
    history.forEach(item => {
      if (historyArr.indexOf(item) == -1) {
        historyArr.push(item)
      }
    })
    wx.setStorageSync("history", historyArr);
    that.setData({
      searchList: [],
      bool: true
    })
    that.fnGetSearchList();
  },
  fnGetSearchList() {
    let that = this;
    let key = that.data.key;
    let _searchKey = that.data.searchValue;
    let data = {
      cur: that.data.query.cur,
      pageSize: that.data.query.pageSize,
    }
    if (key == 1) {
      data.keyword = that.data.searchValue;
      data.px = 2;
      data.orderby = "upcase";
      data.userId = that.data.userId;
      data.project = "lyhad"
    } else {
      data.keyword = that.data.searchValue;
      data.resType = 1;
      data.orderby = "sort";
      data.isOpera = 1;
    }
    let bool = this.data.bool;
    if (!bool) {
      return false;
    };
    let api_url = key == 1 ? "api_getAlbumList" : "api_getArtistList";
    http.lhxRequest(api_url, data).then(res => {
      if (res.code === 10000000) {
        let searchList = this.data.searchList.length > 0 ? this.data.searchList : [];
        for (let i in res.pb.dataList) {
          searchList.push(res.pb.dataList[i])
        }
        if (res.pb.dataList.length <= res.pb.pageSize && res.pb.cur === res.pb.totalPage) {
          this.setData({
            bool: false
          })
        }
        that.setData({
          searchList: searchList
        })
      }
    })
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    let that = this;
    that.setData({
      indexList: [],
      ['query.cur']: 1,
      bool: true
    })
    that.fnGetSearchList()
  },
  onReachBottom: function () {
    let that = this;
    let bool = that.data.bool;
    that.setData({
      ['query.cur']: that.data.query.cur += 1,
    })
    if (!bool) {
      wx.showToast({
        title: "没有更多数据",
        icon: "none",
        duration: 2000,
      });
    }
    that.fnGetSearchList();
  },
  // 进入名家详情
  fnFamousDetails(e) {
    let artistCode = e.currentTarget.dataset.code;
    wx.navigateTo({
      url: "/pages/famous_details/famous_details?artistCode=" + artistCode,
    })
  },
  // 点击历史‘
  fnGetHistory(e) {
    let value = e.currentTarget.dataset.value;
    this.setData({
      searchValue: value,
      bool: true,
      name: false
    })
    this.fnGetSearchList();
  },
  // 跳到详情
  fnJumpDetail(e) {
    const code = e.currentTarget.dataset.code;
    wx.navigateTo({
        url: "/pages/album_details/album_details?code=" + code,
    })
  },
  // 日志
  uniteLog(data) {
    http.lhxRequest("api_log", data).then(res => {
      if (res.code === 10000000) {
        console.log("日志")
      }
    })
  }
})